package com.deductive.netty.udp;

import com.deductive.netty.udp.handler.UdpMessageHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioDatagramChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

@Component
public class NettyUdpServer {

    private static final Logger logger = LoggerFactory.getLogger(NettyUdpServer.class);

    @Autowired
    private UdpMessageHandler udpMessageHandler;

    private EventLoopGroup group;

    @PostConstruct
    public void start() throws Exception {
        int workerThreads = Runtime.getRuntime().availableProcessors() * 2;
        group = new NioEventLoopGroup(workerThreads);

        Bootstrap b = new Bootstrap();
        b.group(group)
                .channel(NioDatagramChannel.class) // 指定使用UDP Channel
                .handler(udpMessageHandler)  // 设置消息处理器
                .option(ChannelOption.SO_BROADCAST, true) // 支持广播
                .option(ChannelOption.SO_RCVBUF, 1024 * 1024) // 设置接收缓冲区大小
                .option(ChannelOption.SO_SNDBUF, 1024 * 1024); // 设置发送缓冲区大小

        ChannelFuture future = b.bind(8083).sync();
        if (future.isSuccess()) {
            logger.info("高性能Netty UDP服务器已在端口8083启动");
        } else {
            logger.error("启动Netty UDP服务器失败", future.cause());
        }
    }

    @PreDestroy
    public void stop() {
        logger.info("正在关闭Netty UDP服务器...");
        if (group != null) {
            group.shutdownGracefully();
        }
        logger.info("Netty UDP服务器已关闭");
    }
}

